package org.gesplan.controller;

import java.util.List;
import java.util.logging.Level;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.swing.JOptionPane;

import org.gesplan.entity.Task;
import org.gesplan.entity.Work;
import org.gesplan.exceptions.NonexistentEntityException;
import org.gesplan.util.Utils;


/**
 *
 * @author Roger
 */
public class WorkJpaController {

    private EntityManagerFactory emf = null;
    
	
    public WorkJpaController() {
        this.emf = Utils.getEntityManagerFactory();
    }

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Work work) {
        
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            em.persist(work);
            em.getTransaction().commit();
            Object[] params = new Object[1];
            params[0] = work.getId();
            Utils.execFunction("select var.set_work_hours(?)", params);                
        } catch (Exception e){
            String msg = Utils.getBundle().getString("ERROR_DB_CREATE") + "\n" + Utils.getBundle().getString("SEE_LOG") + Utils.getLogger().getName();
            JOptionPane.showMessageDialog(null, msg, null, JOptionPane.ERROR_MESSAGE);
            Utils.getLogger().log(Level.SEVERE, e.getMessage());
            // Reset work sequence
            Object[] params = new Object[2];
            params[0] = "public";                        
            params[1] = "work";            
            Utils.execFunction("select var.reset_sequence(?, ?)", params);            
        } finally {
            if (em != null) {
                em.close();
            }
        }
        
    }

    
    public void edit(Work work) throws NonexistentEntityException, Exception {
        
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Work persistentWork = em.find(Work.class, work.getId());
            Task taskIdOld = persistentWork.getTaskId();
            Task taskIdNew = work.getTaskId();
            if (taskIdNew != null) {
                taskIdNew = em.getReference(taskIdNew.getClass(), taskIdNew.getId());
                work.setTaskId(taskIdNew);
            }
            work = em.merge(work);
            if (taskIdOld != null && !taskIdOld.equals(taskIdNew)) {
                taskIdOld.getWorkCollection().remove(work);
                em.merge(taskIdOld);
            }
            if (taskIdNew != null && !taskIdNew.equals(taskIdOld)) {
                taskIdNew.getWorkCollection().add(work);
                em.merge(taskIdNew);
            }
            em.getTransaction().commit();
            Object[] params = new Object[1];
            params[0] = work.getId();
            Utils.execFunction("select var.set_work_hours(?)", params);                
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = work.getId();
                if (findWork(id) == null) {
                    throw new NonexistentEntityException("The work with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
        
    }

    
    public void destroy(Integer id) throws NonexistentEntityException {
        
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Work work;
            try {
                work = em.getReference(Work.class, id);
                work.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The work with id " + id + " no longer exists.", enfe);
            }
            Task taskId = work.getTaskId();
            if (taskId != null) {
                taskId.getWorkCollection().remove(work);
                em.merge(taskId);
            }
            em.remove(work);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
        
    }
    

    public List<Work> findWorkEntities() {
        return findWorkEntities(true, -1, -1);
    }

    public List<Work> findWorkEntities(int maxResults, int firstResult) {
        return findWorkEntities(false, maxResults, firstResult);
    }

    
    @SuppressWarnings({ "rawtypes", "unchecked" })    
    private List<Work> findWorkEntities(boolean all, int maxResults, int firstResult) {
        
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Work.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
        
    }

    
    public Work findWork(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Work.class, id);
        } finally {
            em.close();
        }
    }

    
    @SuppressWarnings({ "rawtypes", "unchecked" })    
    public int getWorkCount() {
        
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Work> rt = cq.from(Work.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
        
    }
    
    
}